package com.tianqu.tms.www.car.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.WeChatMqApi;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn000601Bo;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn30500Bo;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.www.car.action.CarTimeDateCheckInfoAjaxAction;

/**
 * 库存挂起解挂-临时进出时间设定 controller
 * @author mufeiyu
 *
 */
public class CarTimeDateCheckInfoController extends TmsController {
	private Logger logger = Logger.getLogger(CarTimeDateCheckInfoController.class);
	public final static String PUSH_LICENSEPLATE_STR = "【临时进出通知】您车行所登记的库存车辆（｛车辆名称｝，｛车牌号码｝）在｛当前系统时间｝被设定临时进出，时间为 ｛临时进出时间｝，此时间段内车辆可以正常进出门禁系统。";
	public final static String PUSH_VIN_STR = "【临时进出通知】您车行所登记的库存车辆（｛车辆名称｝，｛VIN码｝）在｛当前系统时间｝被设定临时进出，时间为 ｛临时进出时间｝，此时间段内车辆可以正常进出门禁系统。";
	public final static String CAR_NAME = "车辆名称";
	public final static String CAR_NUMBER = "车牌号码";
	public final static String CAR_VIN = "VIN码";
	public final static String SYSTEM_TIME = "当前系统时间";
	public final static String STORAGEENTER_TIME = "临时进出时间";
	public final static String SIGN = "\\$";
	public final static String BEFOREBRACE = "｛";
	public final static String LATERBRACE = "｝";
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			
			String serial = (String)uc.getAttribute(CarTimeDateCheckInfoAjaxAction.SERIAL);
			String storageEnterDate = (String)uc.getAttribute(CarTimeDateCheckInfoAjaxAction.STORAGEENTERDATE);
			String storageTime = (String)uc.getAttribute(CarTimeDateCheckInfoAjaxAction.STORAGETIME);
			
			String isPushStr = (String)uc.getAttribute(CarTimeDateCheckInfoAjaxAction.ISPUSH);
			
			TmsUserProfile profile = uc.getUserProfile();
			Car car = new Car();
			String storageTimes = storageEnterDate +" "+ storageTime;
			String current = DateUtil.getCurrentTime();
			SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 设置日期格式 
			Timestamp tmpStorageTime = new Timestamp(datef.parse(storageTimes).getTime()) ;
			Timestamp currentTime = new Timestamp(datef.parse(current).getTime()) ;
			
			car.setSerial(serial);//车辆编号	
			car.setTmpStorageTime(currentTime);//临时进出开始时间
			car.setTmpEnterTime(tmpStorageTime);//临时进出结束时间
			//更新 库存车辆信息表（tms_market_car_info）
			car.updateTmpStorageEnterTime(car);
			
			Car car1 = new Car();
			int isPush = Integer.valueOf(isPushStr);
			car1.setSerial(serial);//车辆编号
			car1.setHandleType(15);//操作类型
			car1.setIsPush(isPush);//是否推送			
			car1.setUpdateUserId(profile.getUniqueId());//更新用户
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式 			
			String updataTime = DateUtil.getCurrentTime();
			Date dateTime = df.parse(updataTime);
			car1.setUpdateTime(dateTime);//更新时间
			String pushContent = "";
			if(isPush == 1)
			{
				String storageEnterTime =  datef.parse(current).getTime() + " ~ " + tmpStorageTime;
				if(!StringUtil.isNullOrBlank(car.getLicensePlate()))
				{
					pushContent = getPushContent(car.getCarName(),car.getLicensePlate(),dateTime,storageEnterTime,1);
				} else{
					pushContent = getPushContent(car.getCarName(),car.getVin(),dateTime,storageEnterTime,2);
				}			
			}
			car1.setPushContent(pushContent);//推送内容
			//插入 库存车辆特殊处理记录表（tms_market_car_handleInfo）
			car1.insertCarHandleInfo(car1);
			controller.commit();
			if(isPush == 1){
				//接口编号：601；【TMS_web】=》微信终端
				TransferDataSyn000601Bo transferDataSyn000601Bo = new TransferDataSyn000601Bo();
				car = car.findMemberId(serial);
				transferDataSyn000601Bo.setMemberId(car.getMemberId());
				transferDataSyn000601Bo.setPushContent(pushContent);
	
				WeChatMqApi.getInstance().call(transferDataSyn000601Bo);
			}
			
			//
			MobileMessage message = new MobileMessage();
			message.putValue("Serial", car.getSerial());
			message.setMessage("【TMS】挂起/解挂 =》【车代办】同步,Serial为#Serial#");
			Car carInfo = Car.getInstance();
			carInfo = carInfo.findCarBySerial(serial);
			if(carInfo != null)
			{
				TransferDataSyn30500Bo api = new TransferDataSyn30500Bo();
				api.setMobileMessage(message);
				api.setBarCodeNum(carInfo.getBarCodeNum());
				api.setSerial(carInfo.getSerial());
				api.setMemberId(String.valueOf(carInfo.getMemberId()));
				api.setStartTime(StringUtil.getTimeByTimeStamp(carInfo.getTmpStorageTime()));
				api.setEndTime(StringUtil.getTimeByTimeStamp(carInfo.getTmpEnterTime()));
				api.setIsPush(carInfo.getIsPush());
				api.setPushContent(carInfo.getPushContent());
				api.setMarketNo(TmsConstants.MARKET_NO);
				PullingExecutor.getInstance().submit(api);
			}
			
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}
	public String getPushContent(String carName,String carInfo,Date systemTime ,String storageEnterTime, int type)throws TmsDaoException {
		String contentStr = "";
		//车牌号不为空
		if(type == 1 && carInfo.length() >5)
		{
			carInfo = carInfo.substring(carInfo.length()-5, carInfo.length());
			contentStr = PUSH_LICENSEPLATE_STR;
		} else if(type == 2 && carInfo.length() >6){
			carInfo = carInfo.substring(carInfo.length()-6, carInfo.length());
			//车牌号为空
			contentStr = PUSH_VIN_STR;
		}
		contentStr = contentStr.replaceAll(SIGN, "").replaceAll(BEFOREBRACE, "").replaceAll(LATERBRACE, "");
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 设置日期格式
		String sysTime = fm.format(systemTime);
		
		contentStr = contentStr.replaceAll(CAR_NAME, carName).replaceAll(CAR_NUMBER, carInfo)
		.replaceAll(CAR_VIN, carInfo).replaceAll(SYSTEM_TIME, sysTime).replaceAll(STORAGEENTER_TIME, storageEnterTime); 
		
		return contentStr;
	}
}
